package com.spring.demo.springdemo.config;

import com.spring.demo.springdemo.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author RenPu
 * @Date 2024/2/18 14:05
 * @Version 1.0
 * @Description: mybatis框架集成spring的配置类
 *               将mybatis得《mapper 接口》生成得代理类对象，交由spring进行管理
 *
 **/

public class MybatisFactoryBeanConf implements FactoryBean {

    private Class mapperInterface;

//    private SqlSession sqlSession;

    public MybatisFactoryBeanConf(Class interfaceClass) {
        this.mapperInterface = interfaceClass;
    }


//    @Autowired
//    public void setSqlSession(SqlSessionFactory sqlSessionFactory) {
//        sqlSessionFactory.getConfiguration().addMapper(mapperInterface);
////        this.sqlSession = sqlSessionFactory.openSession();
//
//    }

    @Override
    public Object getObject() throws Exception {

        Object newProxyInstance = Proxy.newProxyInstance(MybatisFactoryBeanConf.class.getClassLoader(), new Class[]{mapperInterface}, new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                System.out.println("userMapper中被调用得方法==========="+method.getName());
                return null;
            }
        });


        return newProxyInstance;

//        return sqlSession.getMapper(mapperInterface);



    }

    @Override
    public Class<?> getObjectType() {
        return mapperInterface;
    }
}
